package m202401.d04;

import java.util.ArrayList;
import java.util.List;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/1/4 08:57
 */
//57. 插入区间
public class Q57 {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        if (intervals.length == 0) {
            return new int[][]{newInterval};
        }
        List<int[]> list = new ArrayList<>();
        int min = newInterval[0];
        int max = newInterval[1];
        int index = 0;
        boolean flag = false;
        for (int i = 0; i < intervals.length; i++) {
            int[] current = intervals[i];
            if (current[1] < min) {
                list.add(current);
                continue;
            }
            if (current[0] > max) {
                list.add(new int[]{min, max});
                list.add(current);
                index = i + 1;
                flag = true;
                break;
            }
            min = Math.min(current[0], min);
            max = Math.max(current[1], max);

        }
        if (!flag) {
            list.add(new int[]{min, max});
        }
        for (int i = index; i < intervals.length && flag; i++) {
            list.add(intervals[i]);
        }
        return list.toArray(new int[list.size()][2]);
    }
}
